﻿Imports System.Drawing
Imports System.Net
Imports System.IO
Imports System.Drawing.Printing

Public Class PrinterDrawing

    Public DocList As List(Of PrintDoc)
    Public Printers As New List(Of PrinterControl.PrinterConfig)

    Public Sub DocIteration(ByVal docments)
        DocList = docments
        Printers.Add(PrinterControl.ParsePrinterConfig(My.Settings.Printer_1))
        Printers.Add(PrinterControl.ParsePrinterConfig(My.Settings.Printer_2))
        Printers.Add(PrinterControl.ParsePrinterConfig(My.Settings.Printer_3))
        Printers.Add(PrinterControl.ParsePrinterConfig(My.Settings.Printer_4))

        For Each doc In DocList
            Me.PrinterSwitcher(doc)
        Next
    End Sub

    Public Sub PrinterSwitcher(ByVal doc As PrintDoc)
        For Each printer In Printers
            If (printer.ConEnable) Then
                DocPrinter(doc, printer.ConName)
            End If
        Next
    End Sub

    Public Sub DocPrinter(ByVal doc As PrintDoc, ByVal printer As String)

        Try
            Dim printDoc As New System.Drawing.Printing.PrintDocument

            printDoc.PrinterSettings.PrinterName = printer

            Dim PrintStandard As PrintController = New StandardPrintController(）
            printDoc.PrintController = PrintStandard

            Dim ps As New PageSettings

            ps.PaperSize = New System.Drawing.Printing.PaperSize("Custom Pape", doc.paper_width, doc.paper_height) '设置为指定的纸张
            ps.Landscape = False
            printDoc.DefaultPageSettings = ps

            Document = doc
            AddHandler printDoc.PrintPage, AddressOf Me.PrintCmd
            printDoc.Print()
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Sub

    Dim Document As PrintDoc
    Private Sub PrintCmd(ByVal sender As Object, ByVal ev As System.Drawing.Printing.PrintPageEventArgs)

        Dim label As PrintDoc = Document
        Dim x_ As Integer = 0
        Dim y_ As Integer = 0

        For Each cmd As PrinterCmd In label.cmds

            If (cmd.type.Equals("text")) Then
                ev.Graphics.DrawString(cmd.content, New Font(cmd.content, cmd.font_size), Brushes.Black, cmd.x + x_, cmd.y + y_)
            ElseIf (cmd.type.Equals("image")) Then
                Dim wc As New WebClient()
                Dim bytes As Byte() = wc.DownloadData(cmd.src)
                Dim ms As New MemoryStream(bytes)
                ev.Graphics.DrawImage(System.Drawing.Image.FromStream(ms), cmd.x + x_, cmd.y + y_, cmd.font_size, cmd.font_size)
            ElseIf (cmd.type.Equals("line")) Then
                ev.Graphics.DrawLine(SystemPens.ControlText, cmd.x + x_, cmd.y + y_, cmd.x + x_ + cmd.width, cmd.y + y_)
            End If

        Next

        ev.HasMorePages = False

    End Sub

End Class
